package com.fyy.zookeeper.anli;

import org.apache.zookeeper.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author fyy
 * @Description 客户端实现
 * @Date 2020/11/12 9:48
 */
public class ZKClient {

    private static String connectString = "host1:2181,host2:2181,host3:2181"; //ZK集群
    private static int sessionTimeout = 2000; //会话过期时间2s,单位：ms
    private static ZooKeeper zkClient;

    public static void main(String[] args) throws Exception {
        ZKClient zkClient = new ZKClient();

        //连接ZK集群
        zkClient.getConnect();
        //注册监听
        zkClient.registListen();
        //业务处理
        zkClient.business();
    }

    /**
     * @Author fyy
     * @Description 连接ZK集群
     * @Date 2020/11/12 9:52
     */
    private void getConnect() throws Exception {
        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                try {
                    registListen(); //这里一定要调用监听方法，否则自会监听一次
                } catch (Exception e) {
                    System.out.println("服务器动态上下线监听异常！");
                }
            }
        });
    }

    /**
     * @Author fyy
     * @Description 注册监听
     * @Date 2020/11/12 9:52
     */
    private void registListen() throws KeeperException, InterruptedException {
        List<String> childrens = zkClient.getChildren("/servers", true);
        ArrayList<String> hosts = new ArrayList<String>(); //服务器集合
        for (String children : childrens) {
            byte[] data = zkClient.getData("/servers/" + children, false, null);
            hosts.add(new String(data));
        }
        System.out.println(hosts);
    }

    /**
     * @Author fyy
     * @Description 业务处理
     * @Date 2020/11/12 9:52
     */
    private void business() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

}
